<?php
namespace dk\traits;

trait Rowrelation {
    
    protected $hasRelation = true;
    protected $rowRelation;
    
    protected function getByRelation($key){
        if(!$this->getRowRelation()){
            return false;
        }
        
        if($this->rowRelationInfo && isset($this->rowRelationInfo[$key])){
            return $this->rowRelationInfo[$key];
        }
        
        if(isset($this->rowRelationMap[$key])){
            $objName = $this->rowRelationMap[$key];
            $obj = $this->rowRelationObj[$objName];
            $pk = $this->rowRelation->getConf($objName, 'pk');
            $id = $this->$pk;
            if($id){
                if($info = $obj->onSelect($id)){
                    $this->rowRelationInfo = array_merge($this->rowRelationInfo, $info);
                }
            }
            foreach ($this->rowRelationMap as $k => $v) {
                if($v == $objName){
                    unset($this->rowRelationMap[$k]);
                }
            }
            unset($this->rowRelationObj[$objName]);
            return gav($this->rowRelationInfo, $key);
        }
    }
    
    protected function initRelationMap(){
        $rel = $this->rowRelation->getRelations();
        foreach ($rel as $name => $item) {
            $columns = $item->getColumns();
            foreach ($columns as $value) {
                $this->rowRelationMap[$value] = $name;
            }
            $this->rowRelationObj[$name] = $item;
        }
    }

    protected $rowRelationMap;
    protected $rowRelationObj;
    protected $rowRelationInfo = [];

    public function getRowRelation(){
      
        if(!$this->hasRelation){
            return false;
        } if($this->rowRelation){
           return true ;
        } else {
            $this->rowRelation = $this->getRelationClass();
            $this->initRelationMap();
            return true;
        }
        $this->hasRelation = false;
    }
    
    protected function getRelationClass(){}
}